package com.hdoit.kylin.web.user.provider;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.PageContext;

import org.apache.poi.util.StringUtil;
import org.springframework.jca.cci.core.support.CciDaoSupport;
import org.springframework.util.StringUtils;

import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.logical.superbase.model.Role;
import com.tennetcn.common.logical.superbase.service.IRoleEmployeeService;
import com.tennetcn.common.logical.superbase.service.IRoleService;
import com.tennetcn.common.logical.viewmodel.superbase.RoleSearch;
import com.tennetcn.common.message.ListItem;
import com.tennetcn.common.utils.PageContextUtils;
import com.tennetcn.component.attribute.provider.IMultipleOptionListProvider;
import com.tennetcn.component.attribute.provider.ISingleOptionListProvider;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;

public class StudentRoleProvider implements
		IMultipleOptionListProvider<ListItem> {
	private List<ListItem> dataList;

	@Override
	public List<ListItem> getDataList(Object viewData) {
		List<Role> roles = getRoles();
		if (roles == null || roles.size() <= 0) {
			return null;
		}
		dataList = new ArrayList<ListItem>();
		ListItem listItem;
		for (Role role : roles) {
			listItem = new ListItem();
			listItem.setText(role.getRoleName());
			listItem.setValue(role.getRoleId());

			dataList.add(listItem);
		}
		return dataList;
	}

	private List<Role> getRoles() {
		IRoleService roleService = CommonApplicationContextUtil
				.getCurrentContext().getBean(IRoleService.class);

		return roleService.queryListByMark("student");
	}

	private List<String> getRoleIdsByEmployeeId(String employeeId) {
		IRoleEmployeeService roleEmployeeService = CommonApplicationContextUtil
				.getCurrentContext().getBean(IRoleEmployeeService.class);
		return roleEmployeeService.queryRoleIdsByEmployeeId(employeeId);
	}

	@Override
	public List<ListItem> getSelectedItems(Object value, Object viewData) {
		if (null == dataList || 0 >= dataList.size())
			return null;

		if (StringUtils.isEmpty(value)) {
			PageContext pageContext = (PageContext) viewData;
			String employeeId = PageContextUtils.getParam(pageContext, "key");

			List<String> roleIds = getRoleIdsByEmployeeId(employeeId);

			if (roleIds == null || roleIds.size() <= 0) {
				return null;
			}
			List<ListItem> selDataList = new ArrayList<ListItem>();
			for (String roleId : roleIds) {
				ListItem listItem = Enumerable.init(dataList)
						.filter(data -> roleId.equals(data.getValue())).first();
				if (listItem != null) {
					selDataList.add(listItem);
				}
			}
			return selDataList;
		}
		return null;
	}

}
